#import "HYRequestBaseHelper.h"
#import <HYNetWorkManager.h>
#import "AFNetworkActivityIndicatorManager.h"

#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}

@implementation HYRequestBaseHelper

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

#pragma mark - get请求
+ (NSURLSessionDataTask *)GET:(NSString *)url parameters:(id)parameters success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock {
    CLog(@"url -- %@",url);
    return [self GET:url parameters:parameters headers:nil success:successBlock failure:failureBlock];
}

+ (NSURLSessionDataTask *)GET:(NSString *)url parameters:(id)parameters headers:(NSDictionary *)headers success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager HY_defaultManagerWithURL:url];
    [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    NSURLSessionDataTask *task = [manager GET:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *errorData = [error.userInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:errorData options:NSJSONReadingAllowFragments error:nil];
        NSString *errorStr = @"";
        if([[dic allKeys] containsObject:@"errno"]){
            errorStr = [NSString stringWithFormat:@"%@",[dic valueForKey:@"errno"]];
        }
        if(failureBlock){
          failureBlock(error,errorStr);
        }
    }];
    return task;
}

+ (void)POST:(NSString *)url parameters:(id)parameters success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock {
    [HYRequestBaseHelper POST:url parameters:parameters headers:nil success:successBlock failure:failureBlock];
}

+ (NSURLSessionDataTask *)POST:(NSString *)url parameters:(id)parameters headers:(NSDictionary *)headers success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock {
    if (![self isNetworkAvailable]) {
        if(failureBlock){
            failureBlock(nil,nil);
        }
        return nil;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager HY_defaultManagerWithURL:url];
    [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    NSURLSessionDataTask *ret = [manager POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse *res = (id)task.response;
            NSDictionary *headers = [res allHeaderFields];
            if ([headers isKindOfClass:[NSDictionary class]]) {
                NSString *timeString = [headers objectForKey:@"Date"];
            }
        }
        //统一处理错误信息
        if (![responseObject[@"success"] isEqualToString:@"true"]) {
            
        }
        
        if(successBlock){
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if(failureBlock){
            failureBlock(error,nil);
        }
        
    }];
    return ret;
}

+ (void)PUT:(NSString *)url parameters:(id)parameters success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    if (![self isNetworkAvailable]) {
        return;
    }
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = HY_HTTP_NET_TIMEOUT;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"text/html",@"application/json", nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = HY_HTTP_NET_TIMEOUT;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    [manager PUT:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //统一处理错误信息
        if (![responseObject[@"success"] isEqualToString:@"true"]) {
            
        }
        if (successBlock) {
            successBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error,nil);
        }
    }];
}

#pragma mark - DELETE请求
/**
 *  DELETERequestWithURL
 *
 *  @param url          url
 *  @param parameters   参数
 *  @param successBlock 成功
 *  @param failureBlock 失败
 */
+ (void)DELETE:(NSString *)url parameters:(id)parameters success:(HYHttpRequestSuccess)successBlock failure:(HYHttpRequestError)failureBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    if (![self isNetworkAvailable]) {
        if(failureBlock){
            failureBlock(nil,nil);
        }
        return;
    }
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = HY_HTTP_NET_TIMEOUT;
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = HY_HTTP_NET_TIMEOUT;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"text/html",@"application/json", nil];
    
    [manager DELETE:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //统一处理错误信息
        if (![responseObject[@"success"] isEqualToString:@"true"]) {
        }
        
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error,nil);
        }
    }];
}

#pragma mark - 判断网络状态
+ (BOOL)isNetworkAvailable {
    BOOL rect = [[HYNetWorkManager shareManager] currentReachabilityStatus];
    if (!rect) {
    }
    return rect;
}

#pragma mark - 展示网络信息请求

+ (NSSet *)defaultAcceptableContentTypes {
    return [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"charset=utf-8",@"application/x-mpegURL",@"application/x-www-form-urlencoded", nil];
}

@end

@implementation AFHTTPSessionManager (HY)

+ (AFHTTPSessionManager *)HY_defaultManagerWithURL:(NSString *)url {
    //设置证书
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = HY_HTTP_NET_TIMEOUT;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer.acceptableContentTypes = [HYRequestBaseHelper defaultAcceptableContentTypes];
    manager.requestSerializer.timeoutInterval = 10.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"charset=utf-8",@"application/x-mpegURL",@"application/x-www-form-urlencoded", nil];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    return manager;
}

@end


@implementation HYRequestBaseHelper (GET)

+ (NSURLSessionDataTask *)GET:(NSString *)url parameters:(id)parameters headers:(NSDictionary *)headers completion:(requestCompletion)completionBlock {
    NSURLSessionDataTask *task =
    [self GET:url parameters:parameters headers:headers success:^(id responseObject) {
        if (completionBlock) {
            completionBlock(responseObject,nil,nil);
        }
    } failure:^(NSError *error, NSString *errorStr) {
        if (completionBlock) {
            completionBlock(nil,error,errorStr);
        }
    }];
    return task;
}

@end

@implementation HYRequestBaseHelper (POST)

+ (NSURLSessionDataTask *)POST:(NSString *)url parameters:(id)parameters headers:(NSDictionary *)headers completion:(requestCompletion)completionBlock {
    NSURLSessionDataTask *task =
    [self POST:url parameters:parameters headers:headers success:^(id responseObject) {
        if (completionBlock) {
            completionBlock(responseObject,nil,nil);
        }
    } failure:^(NSError *error, NSString *errorStr) {
        if (completionBlock) {
            completionBlock(nil,error,errorStr);
        }
    }];
    return task;
}

@end

@implementation HYRequestBaseHelper (HYTDownload)

+ (NSURLSessionDownloadTask *)download:(NSString *)url
                            parameters:(id)parameters
                               headers:(NSDictionary *)headers
                              progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
                           destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                     completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError * error))completionHandler {
    if ([self isNetworkAvailable] == false) {
        dispatch_main_async_safe(^{
            if (completionHandler) {
                completionHandler(nil,nil,[NSError errorWithDomain:NSLocalizedString(@"请连接到网络", nil) code:1000 userInfo:nil]);
            }
        });
        return nil;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager HY_defaultManagerWithURL:url];
    [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
    NSDate *startRequestTime = [NSDate date];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSString *tmpDownloadPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
    
    NSURLSessionDownloadTask *task  = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        if (destination) {
            return destination(targetPath,response);
        }
        return [NSURL fileURLWithPath:tmpDownloadPath];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"下载时长: %f",[[NSDate date] timeIntervalSinceDate:startRequestTime]);
        if (completionHandler) {
            completionHandler(response,filePath,error);
        }
    }];
    return  task;
}

@end
